package link.tengfei.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ling.tengfei.service.AdminIdService;
import ling.tengfei.service.AdminIdServiceImpl;
import link.tengfei.bean.AdminUser;
import net.sf.json.JSONArray;

/**
 * Servlet implementation class AdminIdServlet
 */
@WebServlet("/adminid")
public class AdminIdServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		AdminIdService adminIdService = new AdminIdServiceImpl();
		PrintWriter writer = response.getWriter();
		String action = request.getParameter("action");
		if (action == null || action == "") {
			request.getRequestDispatcher("/WEB-INF/admin/admin_id.html").forward(request, response);
		} else if (action != null && action.equals("add")) {
			int passid = Integer.parseInt(request.getParameter("passid"));
			boolean flag = adminIdService.findByPassId(passid);
			if (flag) {
				writer.print(1);
			} else {
				int num = adminIdService.addByPassId(passid);
				if (num == 1) {
					writer.print(2);
				} else {
					writer.print(3);
				}
			}
		} else if (action != null && action.equals("totalPage")) {
			int totalNum = adminIdService.findNum();
			int totalPage = (totalNum % 10 == 0) ? totalNum / 10 : totalNum / 10 + 1;
			writer.print(totalPage);
		} else if (action != null && action.equals("changePage")) {
			int page = Integer.parseInt(request.getParameter("page")) * 10 - 10;
			List<AdminUser> users = adminIdService.findByPage(page);
			JSONArray json = JSONArray.fromObject(users);
			writer.print(json);
		}

	}

}
